package com.yang.modules.common.threadpool;

import cn.hutool.core.collection.CollectionUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.function.Consumer;

/**
 * @author Billyang
 * @date 2024/10/12 15:07
 */
@Component
@Slf4j
public class TaskBatchSendUtils {

    @Autowired
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

    public <T> void send(List<T> taskList, Consumer<? super T> consumer) {
        if (CollectionUtil.isEmpty(taskList)) {
            log.info("TaskBatchSendUtils taskList is empty");
            return;
        }
        int size = taskList.size();
        CountDownLatch countDownLatch = new CountDownLatch(size);
        for (T task : taskList) {
            threadPoolTaskExecutor.execute(() -> {
                try {
                    consumer.accept(task);
                } finally {
                    countDownLatch.countDown();
                }
            });
        }
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            log.error("TaskBatchSendUtils countDownLatch await interrupt", e);
        }
        log.info("TaskBatchSendUtils threadPoolTaskExecutor task finished,size:{}", size);
    }


    public static void sendCoupon(Integer couponId){
        System.out.println(Thread.currentThread().getName() + "下发优惠券 couponId:" + couponId);
    }

}
